<template>
  <view class="page-container w-[750rpx] mx-auto bg-[#f0f2f5] min-h-screen">
    <!-- 页面loading遮罩 -->
    <view v-if="isLoading" class="loading-overlay fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[9999]">
      <view class="loading-content bg-white rounded-[20rpx] p-[40rpx] flex flex-col items-center">
        <view class="loading-spinner w-[60rpx] h-[60rpx] border-4 border-blue-200 border-t-blue-600 rounded-full animate-spin mb-[20rpx]"></view>
        <text class="text-[28rpx] text-gray-600">加载中...</text>
      </view>
    </view>
    <!-- 头部导航 -->
    <!-- Header -->
    <PageHeader title="" :showBack="true" :onlyBack="true" />
    <view class="header bg-gradient-to-r from-[#4361ee] to-[#3f37c9] text-white p-[30rpx] shadow-md sticky top-0 z-[2]">
      <view class="header-content flex justify-center items-center w-full">
        <view class="header-title text-[36rpx] text-center font-bold flex-1">任务详情 </view>
      </view>
    </view>
    <view v-if="isPublisher" class="container p-[30rpx] bg-[#f9d7f9] text-[20rpx]"> 你是发布者 </view>
    <view v-if="isExecutor" class="container p-[30rpx] bg-[#f9d7f9] text-[20rpx]"> 你是执行者 </view>
    <!-- <view v-if="!isPublisher && !isExecutor" class="container p-[30rpx] bg-[#ffcccc] text-[20rpx]">
      你是访客
    </view> -->

    <view class="container px-[20rpx]">
      <!-- 任务详情卡片 -->
      <view class="task-card bg-white rounded-[30rpx] p-[50rpx] my-[40rpx] shadow-sm">
        <view class="task-header flex flex-col mb-[40rpx]">
          <!-- 标题 -->
          <text class="task-title text-[40rpx] font-bold text-[#212529] mb-[20rpx]">
            {{ title }}
          </text>
        </view>

        <!-- 价格区域（去除左侧内边距，确保左对齐） -->
        <view class="task-price self-start text-[#f72585] pl-0 pr-[40rpx] py-[16rpx] rounded-[60rpx] font-bold text-[36rpx] min-w-[240rpx] border border-[#f72585]">
          <text class="inline-block">¥{{ totalAmount }}</text>
        </view>

        <!-- 任务元信息（使用v-for渲染） -->
        <view class="task-meta flex flex-wrap gap-[30rpx] mb-[50rpx] pb-[40rpx] border-b border-[#e9ecef]">
          <view class="meta-item flex items-center text-[28rpx]" v-for="(meta, index) in taskMeta" :key="index">
            <IconFont font-class-name="iconfont" class-prefix="icon" :name="meta.icon" class="mr-[16rpx] text-[#4361ee]" size="18" />
            <text>{{ meta.text }}</text>
          </view>
        </view>

        <!-- 任务描述 -->
        <view class="mb-[60rpx]">
          <view class="section-title flex items-center text-[36rpx] font-bold mb-[30rpx]">
            <IconFont font-class-name="iconfont" class-prefix="icon" name="renwu" class="mr-[20rpx] text-[#4361ee]" size="36" />
            <text>任务描述</text>
          </view>
          <view class="task-description text-[28rpx] leading-[48rpx]">
            <view>{{ text }}</view>
          </view>
        </view>

        <!-- 任务阶段（使用v-for渲染） -->
        <view class="mb-[60rpx]">
          <view class="section-title flex items-center text-[36rpx] font-bold mb-[30rpx]">
            <IconFont font-class-name="iconfont" class-prefix="icon" name="list-fourliebiao" class="mr-[20rpx] text-[#4361ee]" size="26" />
            <text>任务阶段</text>
          </view>
          <view class="stages-container">
            <view class="stage-card bg-[#f8f9fa] rounded-[24rpx] p-[40rpx] pb-[20rpx] mb-[30rpx] border-l-[8rpx] border-[#4361ee] relative" v-for="(stage, index) in stages" :key="index">
              <!-- 原有内容保持不变 -->
              <view class="stage-header flex mb-[30rpx]">
                <text class="stage-name text-[32rpx] font-semibold">{{ stage.task_description }} </text>
                <view class="stage-time text-[#999] ml-auto" v-if="stage.new_price && stage.new_price != stage.price">
                  <text class="line-through text-[28rpx] text-gray-500">¥{{ stage.price }} </text>
                  <text class="text-red-500 ml-2 text-[32rpx]">¥{{ stage.new_price }} </text>
                </view>
                <text v-else class="stage-price font-bold text-red-500 text-[32rpx] ml-auto">¥{{ stage.price }} </text>
              </view>
              <view class="stage-details pl-[20rpx]">
                <view class="flex items-start mb-[16rpx]" v-for="(detail, i) in stage.details" :key="i">
                  <text class="text-[#4361ee] text-[36rpx] leading-[40rpx] mr-[16rpx]">• </text>
                  <text class="text-[28rpx] leading-[40rpx]">{{ detail }}</text>
                </view>
              </view>

              <!-- 状态显示 -->
              <view class="stage-status flex items-center gap-[10rpx]">
                <view class="text-[20rpx] text-[#999]">任务状态:</view>
                <text class="text-[20rpx]" :class="getStatusTextColor(stage.status)">
                  {{ getStatusLabel(stage.status) }}
                </text>
              </view>

              <!-- 操作按钮区域 -->
              <view class="stage-actions mt-4 flex items-center justify-end flex gap-[10rpx]">
                <template v-if="isPublisher">
                  <nut-button
                    v-show="action != '审核申请'"
                    v-for="action in getPublisherActions(stage.status)"
                    :key="action"
                    class=""
                    size="mini"
                    @click="handlePublisherAction(stage.id, index, action, stage.status)"
                  >
                    {{ action }}
                  </nut-button>
                </template>

                <!-- 执行者操作按钮 -->
                <template v-if="isExecutor">
                  <nut-button v-for="action in getExecutorActions(stage.status)" :key="action" class="" size="mini" @click="handleExecutorAction(stage.id, index, action, stage.status)">
                    {{ action }}
                  </nut-button>
                </template>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 发布者信息 -->
      <view class="mb-[40rpx]">
        <view class="section-title flex items-center text-[36rpx] font-bold mb-[30rpx]">
          <IconFont font-class-name="iconfont" class-prefix="icon" name="service-provider_fill" class="mr-[20rpx] text-[#4361ee]" size="26" />
          <text>任务发布方</text>
        </view>
        <view class="publisher-card bg-white rounded-[30rpx] p-[40rpx] shadow-sm border border-[#e9ecef]">
          <view class="publisher-header flex items-center justify-between mb-[20rpx]">
            <text class="publisher-name text-[36rpx] font-bold">{{ memberName }}</text>

            <nut-button type="success" class="" @click="contactPublisher">
              <IconFont font-class-name="iconfont" class-prefix="icon" name="xiaoxi" class="mr-[16rpx] align-middle" size="20" />
              联系发布方
            </nut-button>
          </view>

          <view class="contact-actions flex justify-center"> </view>
        </view>

        <!-- 平台提示 -->
        <view class="task-card bg-[#e6f7ff] border-l-[8rpx] border-[#1890ff] rounded-[24rpx] p-[40rpx] mt-[40rpx] mb-[120rpx]">
          <view class="flex items-center mb-[30rpx]">
            <IconFont font-class-name="iconfont" class-prefix="icon" name="xinxiinfo21" class="text-[#1890ff] mr-[16rpx]" size="20" />
            <text class="text-[32rpx] font-bold">平台提示</text>
          </view>
          <view class="text-[28rpx] leading-[48rpx]">
            <text class="block">1. 任务资金已全额托管在平台，安全有保障</text>
            <text class="block mt-[16rpx]">2. 任务完成后，资金将按阶段划拨到您的账户 </text>
            <text class="block mt-[16rpx]">3. 平台服务费：普通会员15%，SVIP会员6% </text>
            <text class="block mt-[16rpx]">4. 如有纠纷可申请平台仲裁，保障双方权益 </text>
          </view>
        </view>
      </view>

      <!-- 底部操作栏 -->
      <view class="action-bar fixed bottom-0 left-0 w-full bg-white p-[30rpx] shadow-[0_-2px_10px_rgba(0,0,0,0.1)] flex box-border justify-between items-center">
        <!-- 已停止招聘状态 -->
        <view v-if="status == 5" class="flex items-center flex-1">
          <IconFont font-class-name="iconfont" class-prefix="icon" name="xinxiinfo21" size="20" class="text-[#ff9900] mr-[10rpx]" />
          <text class="text-[28rpx] text-[#ff9900]">已停止招聘，无法报名</text>
        </view>
        <!-- 正常状态 -->
        <template v-else>
          <view class="action-info flex-1 pr-[30rpx]">
            <view>
              任务总金额：
              <text class="total-price text-[36rpx] font-bold text-[#f72585]">¥{{ totalAmount }} </text>
            </view>
            <text class="hint block text-[24rpx] text-[#6c757d]">任务资金已由发布方托管在平台 </text>
          </view>
          <!-- <nut-button v-show="!isExecutor" :type="'primary'" @click="claimTask" :disabled="Tasktext != '领取任务'" :loading="isLoading">
            <template v-if="isLoading">
              <IconFont name="spinner" class="mr-[10rpx] animate-spin" size="28" />
            </template>
            <template v-if="isClaimed">{{ memberName === userInfo.name ? (status == 4 ? "已完成" : "进行中") : Tasktext }}</template>
            <template v-else>{{ Tasktext }}</template>
          </nut-button> -->

          <nut-button v-if="canReceive" :type="'primary'" @click="claimTask" :disabled="Tasktext != '领取任务'" :loading="isLoading">
            {{ btnText }}
          </nut-button>
          <view v-else>
            <nut-button :type="'primary'" disabled v-show="!isPublisher">
              {{ btnText }}
            </nut-button>
          </view>
        </template>
      </view>
    </view>
  </view>

  <!-- 支付密码输入框 -->
  <nut-short-password
    v-model="password"
    v-model:visible="visible"
    :length="6"
    :error-msg="errorMsg"
    :disabled="isVerifying"
    @focus="showKeyboard = true"
    @complete="handleComplete"
    @tips="showTips = true"
  >
  </nut-short-password>

  <!-- 数字键盘 -->
  <nut-number-keyboard v-model="password" v-model:visible="showKeyboard" @blur="showKeyboard = false" :close-on-click-outside="false"> </nut-number-keyboard>

  <!-- 修改金额弹窗 -->
  <nut-popup v-model:visible="showAmountDialog" position="center">
    <view class="amount-dialog bg-white rounded-[24rpx] p-[40rpx] w-[540rpx]">
      <view class="dialog-header text-center mb-[40rpx]">
        <text class="text-[36rpx] font-bold text-[#212529]">修改金额</text>
      </view>

      <view class="dialog-content">
        <view class="amount-info mb-[30rpx]">
          <text class="text-[28rpx] text-[#666666]">原金额：</text>
          <text class="text-[32rpx] font-bold text-[#f72585]">¥{{ currentStageAmount }}</text>
        </view>

        <view class="input-group mb-[30rpx]">
          <text class="text-[28rpx] text-[#666666] mb-[16rpx] block">新金额：</text>
          <nut-input v-model="newAmount" type="digit" placeholder="请输入新金额" class="amount-input" :style="{ border: '2rpx solid #e9ecef', borderRadius: '12rpx', padding: '20rpx' }" />
          <text v-if="amountError" class="text-[24rpx] text-[#FF4D4F] mt-[8rpx] block">{{ amountError }}</text>
        </view>

        <view class="password-group mb-[40rpx]">
          <text class="text-[28rpx] text-[#666666] mb-[16rpx] block">交易密码：</text>
          <nut-input
            v-model="amountPassword"
            type="password"
            placeholder="请输入6位交易密码"
            maxlength="6"
            class="password-input"
            :style="{ border: '2rpx solid #e9ecef', borderRadius: '12rpx', padding: '20rpx' }"
          />
          <text v-if="passwordError" class="text-[24rpx] text-[#FF4D4F] mt-[8rpx] block">{{ passwordError }}</text>
        </view>
      </view>

      <view class="dialog-actions flex gap-[20rpx]">
        <nut-button type="default" class="flex-1" @click="cancelAmountChange"> 取消 </nut-button>
        <nut-button type="primary" class="flex-1" @click="confirmAmountChange" :loading="isUpdatingAmount"> 确定 </nut-button>
      </view>
    </view>
  </nut-popup>

  <!-- 纠纷提示弹窗 -->
  <DisputeModal
    v-model:visible="showDisputeModal"
    :title="disputeModalConfig.title"
    :description="disputeModalConfig.description"
    :actions="disputeModalConfig.actions"
    :additional-info="disputeModalConfig.additionalInfo"
    :confirm-text="disputeModalConfig.confirmText"
    :loading="disputeModalLoading"
    @confirm="handleDisputeConfirm"
    @close="handleDisputeClose"
  />

  <!-- 确认完成弹窗 -->
  <nut-popup v-model:visible="showConfirmModal" position="center">
    <view class="confirm-modal bg-white rounded-[24rpx] p-[40rpx] w-[540rpx]">
      <!-- 关闭按钮 -->
      <view class="close-btn absolute top-[20rpx] right-[20rpx] z-[10]" @click="handleConfirmClose">
        <IconFont name="close" size="20" class="text-[#999999]" />
      </view>

      <!-- 成功图标 -->
      <view class="success-icon flex justify-center mb-[30rpx]">
        <view class="w-[80rpx] h-[80rpx] bg-[#F6FFED] rounded-full flex items-center justify-center">
          <IconFont name="success" size="40" class="text-[#52C41A]" />
        </view>
      </view>

      <!-- 标题 -->
      <view class="modal-title text-center mb-[30rpx]">
        <text class="text-[36rpx] font-bold text-[#52C41A]">确认完成</text>
      </view>

      <!-- 说明文字 -->
      <view class="modal-description mb-[30rpx]">
        <text class="text-[28rpx] text-[#666666] leading-[40rpx]">请确认当前阶段任务已完成，确认后将支付相应金额给执行者。</text>
      </view>

      <!-- 金额信息 -->
      <view class="amount-info bg-[#F6FFED] rounded-[16rpx] p-[30rpx] mb-[30rpx]">
        <view class="flex items-center justify-between">
          <text class="text-[28rpx] text-[#333333]">支付金额：</text>
          <text class="text-[32rpx] font-bold text-[#f72585]">¥{{ stages[currentConfirmStageIndex]?.price || 0 }}</text>
        </view>
      </view>

      <!-- 支付密码输入 -->
      <view class="password-group mb-[40rpx]">
        <text class="text-[28rpx] text-[#666666] mb-[16rpx] block">支付密码：</text>
        <nut-input
          v-model="confirmPassword"
          type="password"
          placeholder="请输入6位支付密码"
          maxlength="6"
          class="password-input"
          :style="{ border: '2rpx solid #e9ecef', borderRadius: '12rpx', padding: '20rpx' }"
        />
        <text v-if="confirmPasswordError" class="text-[24rpx] text-[#FF4D4F] mt-[8rpx] block">{{ confirmPasswordError }}</text>
      </view>

      <!-- 确认按钮 -->
      <view class="modal-actions flex-center">
        <nut-button type="primary" class="w-full" :loading="confirmModalLoading" @click="handleConfirmComplete"> 确认完成 </nut-button>
      </view>
    </view>
  </nut-popup>

  <!-- 客服联系弹窗 -->
  <CustomerServiceModal v-model:visible="showCustomerServiceModal" @close="handleCustomerServiceClose" />

  <!-- VIP 次卡确认弹窗 -->
  <VipCardConfirmModal v-model:visible="showVipConfirm" :card-balance="userInfo.card_balance || 0" @confirm="onVipConfirm" @cancel="onVipCancel" />
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import Taro from "@tarojs/taro";
import { IconFont, RectRight, Success } from "@nutui/icons-vue-taro";
// import { NutButton } from '@nutui/nutui-taro'
import { post } from "@/utils/request";
// import { View } from "@tarojs/components";
import PageHeader from "@/components/PageHeader.vue";
import DisputeModal from "@/components/DisputeModal.vue";
import CustomerServiceModal from "@/components/CustomerServiceModal.vue";
import VipCardConfirmModal from "@/components/VipCardConfirmModal.vue";
import { useUserStore } from "@/store/user";
import { storeToRefs } from "pinia";
import { StatusActions } from "@/constants/StatusActions";
import { View } from "@tarojs/components";

const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);

Taro.useDidShow(() => {
  getTaskDetail();
});

// VIP 次卡确认弹窗
const showVipConfirm = ref(false);
const pendingAction = ref<{ stageId: number; stageIndex: number } | null>(null);

interface CategoryColumn {
  cycle: number; // 周期（数字类型）
  describe_str: string; // 描述字符串
  id: number; // 唯一标识ID
  labels: string; // 标签信息
  memberName: string; // 成员名称
  memberStatus: number; // 成员状态（数字类型表示）
  name: string; // 名称(类别)
  title: string; // 标题
  total_amount: number; // 总金额
  status: null | number; // 状态（可能为null或数字类型）
  taskStages: taskStages[]; // 任务阶段列表，包含多个taskStages类型的元素
}

interface CategoryItem {
  columns: CategoryColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

interface taskStages {
  create_time: number;
  cycle: number;
  id: number;
  price: number;
  status: number;
  task_description: string | null;
  task_id: number;
  update_time: number | null;
}

// 任务渲染
const text = ref();
const Tasktext = ref("领取任务");
const title = ref();
const totalAmount = ref();
// 任务总阶段
const status = ref();
// 登录者身份
const userName = userStore.userInfo.name;
// 发布者用户身份
const memberName = ref("");
// 执行者用户身份
const memberPeople = computed(() => {
  // 根据后端返回的申请人列表进行条件查询（根据当前用户名字来查询）
  return applicationList.value.find((item) => item.name === userStore.userInfo.name && item.status === "1");
});

// 返回登录者身份为发布者
const isMember = computed(() => {
  if (memberName.value !== userStore.userInfo.name) {
    return true;
  }
  return false;
});

const canReceive = computed(() => {
  if(hasRegester.value){ 
    return false;
  }
  if(isPublisher.value){
    return false;
  }
  return true;
});

const isPeople = computed(() => {
  if (memberPeople.value.name === userStore.userInfo.name) {
    return true;
  }
  return false;
});

// 申请人列表用户
const applicationList = ref([
  {
    member_id: "",
    name: "",
    status: "",
  },
]);

// 获取路由参数
const taskId = Taro.getCurrentInstance().router?.params.id;
const deadline = Taro.getCurrentInstance().router?.params.deadline;

// 渲染数据
// const taskData = ref<CategoryColumn>()

// 状态管理
const isLoading = ref(false);
const isClaimed = ref(true);
// 支付状态管理
const visible = ref(false); // 密码框显示状态
const showKeyboard = ref(false); // 键盘显示状态
const password = ref(""); // 输入的密码
const errorMsg = ref(""); // 错误提示
const showTips = ref(false); // 提示弹窗状态
const isVerifying = ref(false); // 验证中状态
const executorList = ref<any[]>([]);

const hasRegester = computed(() => {
  return executorList.value.some((item) => item.member_id == userStore.userInfo.id);
});

const btnText = computed(() => {
  if(hasRegester.value){ 
    return "已报名";
  }
  if(isPublisher.value){
    return "";
  }
  return "领取任务";
});

// 任务元信息数据
const taskMeta = ref([
  { icon: "shijian", text: "截止：2025-07-20" },
  // { icon: 'weizhi', text: '远程任务' },
  { icon: "leibie", text: "设计类" },
  { icon: "yirenzhengyonghu", text: "需实名认证" },
]);

// 任务阶段数据
const stages = ref<taskStages[]>([]);
//用户身份判断
const judgeThePublisher = ref(false);

// 时间戳转换
function formatTimestamp(timestamp: number) {
  const date = new Date(timestamp);
  // 提取各时间部分（注意月份从0开始，需+1）
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 补0成两位数
  const day = String(date.getDate()).padStart(2, "0");

  return `${year}-${month}-${day}`;
}

/**
 * 获取状态标签文字
 * @param status 任务状态码
 * @returns 状态标签文字
 */
const getStatusLabel = (status: number): string => {
  return StatusActions[status as keyof typeof StatusActions]?.label || "未知状态";
};

/**
 * 获取状态文字颜色
 * @param status 任务状态码
 * @returns CSS类名
 */
const getStatusTextColor = (status: number): string => {
  switch (status) {
    case 0:
      return "text-[#FF4D4F]"; // 待完成 - 红色
    case 3:
      return "text-[#52C41A]"; // 已完成 - 绿色
    case 21:
      return "text-[#FAAD14]"; // 待审核 - 橙色
    case 22:
      return "text-[#52C41A]"; // 确认完成 - 绿色
    case 23:
    case 24:
      return "text-[#FF4D4F]"; // 有纠纷/纠纷协商 - 红色
    default:
      return "text-[#666666]"; // 默认灰色
  }
};

/**
 * VIP 次卡确认回调
 */
const onVipConfirm = async (payload: { useVip: boolean }) => {
  if (!pendingAction.value) {
    showVipConfirm.value = false;
    return;
  }
  const { stageId, stageIndex } = pendingAction.value;
  pendingAction.value = null;

  // 使用与“我已完成”一致的状态 21
  const newStatus = 21;

  // 可选：如果选择使用 VIP 次卡，可在此传递额外参数到后端
  const res = await post("/task/updateStage", {
    id: stageId,
    status: newStatus,
    countCard: 0,
    // countCard: payload.useVip ? 1 : 0,
  });

  if (res.code === 0) {
    stages.value[stageIndex].status = newStatus;
    Taro.showToast({ title: "提交成功，待审核", icon: "success", duration: 2000 });
    checkAllStagesCompleted();
  } else {
    Taro.showToast({ title: res.message || "操作失败", icon: "error", duration: 2000 });
  }
};

const onVipCancel = () => {
  pendingAction.value = null;
};

/**
 * 获取发布者操作按钮列表
 * @param status 任务状态码
 * @returns 操作按钮数组
 */
const getPublisherActions = (status: number): string[] => {
  return StatusActions[status as keyof typeof StatusActions]?.publisherActions || [];
};

/**
 * 获取执行者操作按钮列表
 * @param status 任务状态码
 * @returns 操作按钮数组
 */
const getExecutorActions = (status: number): string[] => {
  return StatusActions[status as keyof typeof StatusActions]?.executorActions || [];
};

/**
 * 处理发布者操作
 * @param stageId 阶段ID
 * @param stageIndex 阶段索引
 * @param action 操作名称
 * @param currentStatus 当前状态
 */
const handlePublisherAction = async (stageId: number, stageIndex: number, action: string, currentStatus: number) => {
  try {
    console.log("评价==>", stages.value[stageIndex], stageId);
    let newStatus = currentStatus;

    // 根据操作名称确定新状态
    switch (action) {
      case "确认完成":
        // 设置当前确认完成阶段信息
        currentConfirmStageId.value = stageId;
        currentConfirmStageIndex.value = stageIndex;
        // 显示确认完成弹窗
        showConfirmModal.value = true;
        return;
      case "有纠纷":
        // 设置当前纠纷阶段信息
        currentDisputeStageId.value = stageId;
        currentDisputeStageIndex.value = stageIndex;
        // 显示纠纷弹窗
        showDisputeModal.value = true;
        return;
      case "联系平台":
        // 显示客服联系弹窗
        // showCustomerServiceModal.value = true;
        Taro.navigateTo({
          url: `/pages/webs/contact-us`,
        });
        return;
      case "联系执行者":
        // 跳到聊天
        Taro.navigateTo({
          url: `/pages/message/chat?userId=${executor_member_id.value}`,
        });
        return;
      case "修改金额":
        // 修改金额操作，打开弹窗
        openAmountDialog(stageId, stageIndex, stages.value[stageIndex].price);
        return;
      case "评价":
        const obj = stages.value[stageIndex];
        // 跳转到评价页面
        Taro.navigateTo({
          url: `/pages-detail/post/recruit/evaluate?taskId=${obj.id}&taskName=${obj.task_description}&userName=${executer_name.value}&userAvatar=${executer_avatar_url.value}&userId=${executor_member_id.value}`,
        });

        return;
      default:
        Taro.showToast({
          title: "未知操作",
          icon: "error",
          duration: 2000,
        });
    }

    // 调用接口更新状态
    const res = await post("/task/updateStage", {
      id: stageId,
      status: newStatus,
    });

    if (res.code === 0) {
      // 更新本地状态
      stages.value[stageIndex].status = newStatus;

      Taro.showToast({
        title: "操作成功",
        icon: "success",
        duration: 2000,
      });

      // 检查所有阶段的状态
      checkAllStagesCompleted();
    } else {
      Taro.showToast({
        title: res.message || "操作失败",
        icon: "error",
        duration: 2000,
      });
    }
  } catch (error) {
    console.error("发布者操作失败:", error);
    Taro.showToast({
      title: "网络错误，请重试",
      icon: "error",
      duration: 2000,
    });
  }
};

async function showModal(title: string, content: string) {
  const res = await Taro.showModal({
    title: title,
    content: content,
    confirmText: "确定",
    cancelText: "取消",
  });
  console.log("res==>", res);
  return res.confirm;
}

/**
 * 处理执行者操作
 * @param stageId 阶段ID
 * @param stageIndex 阶段索引
 * @param action 操作名称
 * @param currentStatus 当前状态
 */
const handleExecutorAction = async (stageId: number, stageIndex: number, action: string, currentStatus: number) => {
  try {
    let newStatus = currentStatus;

    // 根据操作名称确定新状态
    switch (action) {
      case "我已完成":
        // 打开 VIP 次卡确认弹窗，待用户确认后再执行提交
        pendingAction.value = { stageId, stageIndex };
        showVipConfirm.value = true;
        return;
      case "联系平台":
        // 显示客服联系弹窗
        // showCustomerServiceModal.value = true;
        Taro.navigateTo({
          url: `/pages/webs/contact-us`,
        });
        return;
      case "联系发布者":
        // 跳到聊天
        Taro.navigateTo({
          url: `/pages/message/chat?userId=${publisher_member_id.value}`,
        });
      // 写一个客服联系方法的弹窗
      case "接受方案":
        const rr = await showModal("接受方案", "确定要接受方案吗？");
        if (!rr) return;
        newStatus = 26; // 确认完成
        const res1 = await post("/task/confirmSettlement", {
          id: stageId,
          // status: newStatus,
          // payPassword: password.value,
          stage: stageIndex + 1,
          // amount: stages.value[stageIndex].price,
        });
        if (res1.code === 0) {
          Taro.showToast({
            title: "方案已接受",
            icon: "success",
            duration: 2000,
          });
        } else {
          Taro.showToast({
            title: res1.data || "方案接受失败",
            icon: "error",
            duration: 2000,
          });
        }
        break;
      case "拒绝方案":
        const rrr = await showModal("拒绝方案", "确定要拒绝方案吗？");
        if (!rrr) return;
        newStatus = 25; // 有纠纷
        const res2 = await post("/task/confirmSettlementRefuse", {
          id: stageId,
          // status: newStatus,
          // payPassword: password.value,
          stage: stageIndex + 1,
          // amount: stages.value[stageIndex].price,
        });
        if (res2.code === 0) {
          Taro.showToast({
            title: "方案已拒绝",
            icon: "success",
            duration: 2000,
          });
        } else {
          Taro.showToast({
            title: res2.data || "方案拒绝失败",
            icon: "error",
            duration: 2000,
          });
        }

        break;
      default:
        Taro.showToast({
          title: "未知操作",
          icon: "error",
          duration: 2000,
        });
        return;
    }

    // 调用接口更新状态
    const res = await post("/task/updateStage", {
      id: stageId,
      status: newStatus,
    });

    if (res.code === 0) {
      // 更新本地状态
      stages.value[stageIndex].status = newStatus;

      Taro.showToast({
        title: "操作成功",
        icon: "success",
        duration: 2000,
      });

      // 检查所有阶段的状态
      checkAllStagesCompleted();
    } else {
      Taro.showToast({
        title: res.message || "操作失败",
        icon: "error",
        duration: 2000,
      });
    }
  } catch (error) {
    console.error("执行者操作失败:", error);
    Taro.showToast({
      title: "网络错误，请重试",
      icon: "error",
      duration: 2000,
    });
  }
};

/**
 * 检查所有阶段是否完成
 */
const checkAllStagesCompleted = async () => {
  // 检查所有阶段的状态是否都为已完成（状态3或状态22都算完成）
  const allStagesCompleted = stages.value.every((stage) => stage.status === 3 || stage.status === 22);

  // 如果所有阶段都完成，则将主任务状态设为已完成
  if (allStagesCompleted) {
    status.value = 4;
    try {
      const res = await post("/task/updateMainStatus", {
        id: Number(taskId),
        status: 4,
      });

      if (res.code !== 0) {
        Taro.showToast({
          title: "主任务状态更新失败",
          icon: "error",
          duration: 2000,
        });
      }
    } catch (error) {
      console.error("主任务状态更新失败:", error);
    }
  }
};

/**
 * 打开修改金额弹窗
 * @param stageId 阶段ID
 * @param stageIndex 阶段索引
 * @param currentAmount 当前金额
 */
const openAmountDialog = (stageId: number, stageIndex: number, currentAmount: number) => {
  currentStageId.value = stageId;
  currentStageIndex.value = stageIndex;
  currentStageAmount.value = currentAmount;
  newAmount.value = currentAmount.toString();
  amountError.value = "";
  amountPassword.value = "";
  passwordError.value = "";
  showAmountDialog.value = true;
};

/**
 * 取消修改金额
 */
const cancelAmountChange = () => {
  showAmountDialog.value = false;
  newAmount.value = "";
  amountError.value = "";
  amountPassword.value = "";
  passwordError.value = "";
};

/**
 * 确认修改金额
 */
const confirmAmountChange = async () => {
  // 验证金额输入
  const amount = parseFloat(newAmount.value);

  if (isNaN(amount) || amount <= 0) {
    amountError.value = "请输入有效的金额";
    return;
  }

  if (amount > currentStageAmount.value) {
    amountError.value = "新金额不能超过原金额";
    return;
  }

  // 验证密码输入
  if (!amountPassword.value || amountPassword.value.length !== 6) {
    passwordError.value = "请输入6位交易密码";
    return;
  }

  // 清除错误提示
  amountError.value = "";
  passwordError.value = "";

  try {
    isUpdatingAmount.value = true;

    // 调用接口修改金额
    const res = await post("/task/confirmPay", {
      amount: amount,
      id: currentStageId.value,
      stage: currentStageIndex.value + 1,
      payPassword: amountPassword.value,
    });

    if (res.code === 0) {
      // 更新本地数据
      stages.value[currentStageIndex.value].price = amount;

      // 重新计算总金额
      totalAmount.value = stages.value.reduce((acc, stage) => acc + stage.price, 0);

      Taro.showToast({
        title: "金额修改成功",
        icon: "success",
        duration: 2000,
      });

      // 关闭弹窗并清空数据
      showAmountDialog.value = false;
      newAmount.value = "";
      amountPassword.value = "";
    } else {
      Taro.showToast({
        title: res.data || "金额修改失败",
        icon: "error",
        duration: 2000,
      });
    }
  } catch (error) {
    console.error("修改金额失败:", error);
    Taro.showToast({
      title: "网络错误，请重试",
      icon: "error",
      duration: 2000,
    });
  } finally {
    isUpdatingAmount.value = false;
  }
};

/**
 * 处理纠纷弹窗确认
 */
const handleDisputeConfirm = async () => {
  disputeModalLoading.value = true;

  try {
    // 调用接口更新状态为有纠纷
    const res = await post("/task/updateStage", {
      id: currentDisputeStageId.value,
      status: 23,
    });

    if (res.code === 0) {
      // 更新本地状态
      stages.value[currentDisputeStageIndex.value].status = 23;

      showDisputeModal.value = false;

      Taro.showToast({
        title: "异议申请已提交",
        icon: "success",
        duration: 2000,
      });
    } else {
      Taro.showToast({
        title: res.message || "操作失败",
        icon: "error",
        duration: 2000,
      });
    }
  } catch (error) {
    console.error("提交异议申请失败:", error);
    Taro.showToast({
      title: "网络错误，请重试",
      icon: "error",
      duration: 2000,
    });
  } finally {
    disputeModalLoading.value = false;
  }
};

/**
 * 处理纠纷弹窗关闭
 */
const handleDisputeClose = () => {
  showDisputeModal.value = false;
};

/**
 * 处理确认完成弹窗确认
 */
const handleConfirmComplete = async () => {
  // 验证支付密码
  if (!confirmPassword.value || confirmPassword.value.length !== 6) {
    confirmPasswordError.value = "请输入6位支付密码";
    return;
  }

  confirmModalLoading.value = true;
  confirmPasswordError.value = "";

  try {
    // 调用确认完成接口
    const res = await post("/task/confirmPay", {
      id: currentConfirmStageId.value,
      amount: stages.value[currentConfirmStageIndex.value].price,
      payPassword: confirmPassword.value,
    });

    if (res.code === 0) {
      // 更新本地状态为确认完成
      stages.value[currentConfirmStageIndex.value].status = 22;

      showConfirmModal.value = false;
      confirmPassword.value = "";

      Taro.showToast({
        title: "方案已确认完成",
        icon: "success",
        duration: 2000,
      });
      post("/task/updateStage", {
        id: currentDisputeStageId.value,
        status: 22,
      });

      // 检查所有阶段的状态
      checkAllStagesCompleted();
    } else {
      confirmPasswordError.value = res.data || "方案确认完成失败";
    }
  } catch (error) {
    console.error("确认完成失败:", error);
    confirmPasswordError.value = "网络错误，请重试";
  } finally {
    confirmModalLoading.value = false;
  }
};

/**
 * 处理确认完成弹窗关闭
 */
const handleConfirmClose = () => {
  showConfirmModal.value = false;
  confirmPassword.value = "";
  confirmPasswordError.value = "";
};

/**
 * 处理客服联系弹窗关闭
 */
const handleCustomerServiceClose = () => {
  showCustomerServiceModal.value = false;
};

// 阶段任务完成处理--修改阶段任务的状态（保留原有方法以兼容）
const confirmStage = async (id: number, index: number) => {
  // API
  const res = await post("/task/updateStage", {
    id: id,
    status: 3,
  });
  if (res.code == 0) {
    // 修改成功 --> 待确认完成状态
    stages.value[index].status = 3;
    // 检查所有阶段的状态是否都为已完成
    const allStagesCompleted = stages.value.every((stage) => stage.status === 3);

    // 如果所有阶段都完成，则将主任务状态设为已完成
    if (allStagesCompleted) {
      status.value = 4;
      await post("/task/updateMainStatus", {
        id: Number(taskId),
        status: 4,
      }).then((res) => {
        if (res.code != 0) {
          Taro.showToast({
            title: "主任务状态更新失败",
            icon: "error",
            duration: 2000,
          });
        }
      });
    }
  }
};

const contactPublisher = () => {
  // 如果memberObj.member_id 和用户id相同，则不打开聊天窗口,提示不能与自己聊天
  if (memberObj.member_id == userInfo.value.id) {
    Taro.showToast({
      title: "不能与自己聊天",
      icon: "none",
      duration: 2000,
    });
    return;
  }
  Taro.navigateTo({
    url: `/pages/message/chat?userId=${memberObj.member_id}&userName=${memberObj.name}`,
  });
};

const handleComplete = async (value: any) => {
  // 基础校验（虽然组件已限制长度，但二次校验更稳妥）
  if (value.length !== 6) {
    errorMsg.value = "请输入6位数字密码";
    return;
  }

  try {
    isVerifying.value = true;
    errorMsg.value = "";

    // 1. 密码加密（实际项目中需对接后端加密规则）
    // const encryptedPwd = encryptPassword(value)

    // 2. 调用后端验证接口（示例）
    const response = await post("/task/confirmPay", {
      id: taskId,
      password: password.value,
    });
    // 测试 == > 扣款成功
    // const response = { code: 1, message: "余额不足" };
    if (response.code == 0) {
      // 验证成功：关闭密码框，清空密码
      visible.value = false;
      showKeyboard.value = false;
      password.value = "";
      // 修改任务状态
      const res = await post("/task/updateStage", {
        id: taskId,
        status: 4,
      });
      if (res.code == 0) {
        Taro.showToast({
          title: "商家点击了确认完成！",
          icon: "success",
          duration: 2000,
        });
      }
    } else {
      // 验证失败：显示错误，保留输入方便修改
      errorMsg.value = response.message || "支付密码错误，请重新输入";
    }
  } catch (err) {
    errorMsg.value = "网络异常，请稍后重试";
    console.error("验证失败：", err);
  } finally {
    isVerifying.value = false;
  }
};

const claimTask = async () => {
  console.log("==>", memberName.value);
  console.log("==>", userStore.userInfo.name);
  console.log("==>", memberPeople.value);
  // if (isClaimed.value) return;
  const isReceive = await userStore.checkIsReceive();
  if(!isReceive) return;

  // 是否商家
  if (isMember) {
    console.log("领取任务");
    // 确认领取
    try {
      if (true) {
        isLoading.value = true;

        // 模拟API请求延迟
        // await new Promise((resolve) => setTimeout(resolve, 1500));
        const res = await post("/task/register", {
          taskId: taskId,
          type: 1,
        });
        console.log("任务领取===>", res);
        Tasktext.value = "已申请";
        if (res.code == 0) {
          isLoading.value = false;
          isClaimed.value = false;

          Taro.showToast({
            title: "任务申请成功！",
            icon: "success",
            duration: 2000,
          });
          // Taro.redirectTo({
          //   url: "/pages/reward/hall",
          // });
        } else {
          isLoading.value = false;
          isClaimed.value = false;
          Taro.showToast({
            title: res.data,
            icon: "none",
            duration: 2000,
          });
        }
      } else {
      }
    } catch (err) {
      isLoading.value = false;
      isClaimed.value = false;
      Taro.showToast({
        title: "请勿重复申请",
        icon: "none",
        duration: 2000,
      });
    }
  } else {
    // 为商家点击确认完成
    visible.value = true;
  }

  // if(memberPeople.value === userName) {

  // }
};
const memberObj = {
  member_id: "",
  name: "",
};

const isExecutor = ref(false);
const isPublisher = ref(false);

// 修改金额相关状态
const showAmountDialog = ref(false);
const newAmount = ref("");
const currentStageAmount = ref(0);
const currentStageId = ref(0);
const currentStageIndex = ref(0);
const amountError = ref("");
const isUpdatingAmount = ref(false);
const amountPassword = ref("");
const passwordError = ref("");

// 纠纷弹窗相关状态
const showDisputeModal = ref(false);
const disputeModalLoading = ref(false);
const currentDisputeStageId = ref(0);
const currentDisputeStageIndex = ref(0);
const disputeModalConfig = ref({
  title: "异议申请已提交",
  description: "我们已收到您的异议申请，平台将立即采取以下措施：",
  actions: [
    { icon: "lock", text: "冻结当前阶段交易资金" },
    { icon: "service", text: "客服将在24小时内联系双方" },
    { icon: "clock", text: "纠纷处理期间暂停任务进度" },
  ],
  additionalInfo: "请准备好相关沟通记录作为证据，平台客服会通过注册手机号与您联系。",
  confirmText: "确认",
});

// 确认完成弹窗相关状态
const showConfirmModal = ref(false);
const confirmModalLoading = ref(false);
const currentConfirmStageId = ref(0);
const currentConfirmStageIndex = ref(0);
const confirmPassword = ref("");
const confirmPasswordError = ref("");

// 客服联系弹窗相关状态
const showCustomerServiceModal = ref(false);
const customerServiceConfig = ref([
  {
    icon: "phone",
    title: "电话客服",
    description: "400-123-4567",
    action: "phone" as const,
    value: "400-123-4567",
  },
  {
    icon: "wechat",
    title: "微信客服",
    description: "扫码添加客服微信",
    action: "wechat" as const,
    value: "customer_service_wechat",
  },
  {
    icon: "email",
    title: "邮件客服",
    description: "service@example.com",
    action: "email" as const,
    value: "service@example.com",
  },
  // {
  //   icon: 'chat',
  //   title: '在线客服',
  //   description: '点击进入在线聊天',
  //   action: 'online' as const,
  //   value: 'online_chat'
  // }
]);

//下拉刷新
// const onPullDownRefresh = async () => {
//   await getTaskDetail();
//   Taro.stopPullDownRefresh();
// };

const executer_name = ref("");
const executer_avatar_url = ref("");
const executor_member_id = ref("");
const publisher_member_id = ref("");

// 任务详情
const getTaskDetail = async () => {
  // 显示loading
  isLoading.value = true;

  try {
    const res = await post("/task/detail", { id: taskId });
    console.log("任务详情==>", res);
    if (res.code == 0) {
      title.value = res.data.columns.title;
      text.value = res.data.columns.describe_str;
      totalAmount.value = res.data.columns.taskStages.reduce((acc, item) => acc + parseFloat(item.columns.price), 0);
      memberName.value = res.data.columns.memberName;
      status.value = res.data.columns.status;
      stages.value = res.data.columns.taskStages.map((item: taskStages) => item.columns);
      taskMeta.value[0].text = `截止：${res.data.columns.deadline}`;
      taskMeta.value[1].text = `${res.data.columns.name}类`;
      applicationList.value = res.data.columns.members.map((item) => item.columns);
      isExecutor.value = res.data.columns.members.some((item: any) => item.columns.member_id == userStore.userInfo.id && (item.columns.status === 11 || item.columns.status > 20));
      // executor_member_id.value = res.data.columns.members.find((item: any) => item.columns.status === 11 || item.columns.status > 20)?.member_id;
      const ary:any[] = [];
      res.data.columns.members.forEach((item: any) => {
        console.log("item===>", item.columns);
        ary.push(item.columns);
        if(item.columns.status === 11 || item.columns.status > 20){
          executor_member_id.value = item.columns.member_id;
          executer_name.value = item.columns.name;
        }
      });
      executorList.value = ary;
      
      isPublisher.value = res.data.columns.member_id == userStore.userInfo.id;
      publisher_member_id.value = res.data.columns.member_id;
      // executer_name.value = res.data.columns.executer_name;
      executer_avatar_url.value = res.data.columns.executer_avatar_url;
      // 调试信息
      console.log("当前用户ID:", userStore.userInfo.id);
      console.log("发布者ID:", res.data.columns.member_id);
      console.log("申请人列表:", res.data.columns.members);
      console.log("是否为执行者:", isExecutor.value, executor_member_id.value);
      console.log("是否为发布者:", isPublisher.value, publisher_member_id.value);
      if (userInfo.value.id == res.data.columns.member_id) {
        judgeThePublisher.value = true;
      }

      memberObj.member_id = res.data.columns.member_id;
      memberObj.name = res.data.columns.memberName;
    }
  } catch (error) {
    console.error("获取任务详情失败:", error);
  } finally {
    // 延时500ms隐藏loading
    setTimeout(() => {
      isLoading.value = false;
    }, 500);
  }
};
// getTaskDetail();

// 下拉刷新处理
const onPullDownRefresh = async () => {
  await getTaskDetail();
  Taro.stopPullDownRefresh();
};

Taro.usePullDownRefresh(onPullDownRefresh);

// 任务类型
</script>
<style scoped lang="scss">
.nnn {
  pointer-events: none;
}

/* Loading动画 */
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.animate-spin {
  animation: spin 1s linear infinite;
}

.loading-overlay {
  backdrop-filter: blur(4rpx);
}

.loading-content {
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}
</style>
